package _binary_search;

/**
 * 34. 在排序数组中查找元素的第一个和最后一个位置
 */
public class No34 {
    public int[] searchRange(int[] nums, int target) {
        int start = lowerBound(nums, target);
        if (start == nums.length || nums[start] != target) return new int[]{-1, -1};
        int end = lowerBound(nums, target + 1) - 1;
        return new int[]{start, end};
    }

    /**
     * 闭区间
     */
    private int lowerBound(int[] nums, int target) {
        int left = 0, right = nums.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] < target) left = mid + 1;
            else right = mid - 1;
        }
        return left;
    }

    /*
      二、模拟（不推荐）
     */
    public int[] searchRange0(int[] nums, int target) {
        int left = 0, right = nums.length - 1;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (nums[mid] < target) {
                left = mid + 1;
            } else if (nums[mid] > target) {
                right = mid - 1;
            } else {
                left = mid;
                right = mid;
                while (left > 0 && nums[left - 1] == nums[mid]) {
                    left--;
                }
                while (right < nums.length - 1 && nums[right + 1] == nums[mid]) {
                    right++;
                }
                return new int[]{left, right};
            }
        }
        return new int[]{-1, -1};
    }
}
